package com.trkj.controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.trkj.pojo.Emp;
import com.trkj.service.EmpService;

/**
 * 文件上传
 * @author skm
 *
 */
@Controller
@SessionAttributes({"emp", "funcIds"})
public class FileUploadController {
	@Autowired
	EmpService empService;
	
	@RequestMapping("/upload")
	public String upload(Emp emp,Model model,
			@RequestParam("file") CommonsMultipartFile file,
			HttpServletRequest request, String desc){
		try {
			System.out.println(desc);
			
			String sqlAvatar = null;
			
			//生成一个全球唯一的字符串
			String newFileName;
			//获取工程所有的物理路径
			ServletContext application = request.getServletContext();
			String root = application.getRealPath("./WEB-INF/css/img");
			System.out.println(root);
			//创建uploads子文件夹
			File rootDir = new File(root);
			if (!rootDir.exists()) {
				rootDir.mkdirs();//创建文件夹
			}
			//获取原始文件的扩展名
			//获取文件的原始名称
			String oldFileName = file.getOriginalFilename();
			System.out.println(oldFileName);
			//找到最后一个.的位置
			int pos = oldFileName.lastIndexOf('.');
			//截取出扩展名
			String ext = oldFileName.substring(pos);
			System.out.println(ext);
			newFileName = UUID.randomUUID().toString().toUpperCase();
			System.out.println(newFileName);
			//拼成完整的文件名
			newFileName = newFileName + ext;
			System.out.println(newFileName);
			//定义新文件的绝对物理路径
			File realFile = new File(rootDir, newFileName);
			//转存...
			file.transferTo(realFile);
			
			//修改头像并把路径保存到数据库
			sqlAvatar = "css/img/"+newFileName;
			emp.setEmpImg(sqlAvatar);
			empService.updateEmpAvatar(emp,emp.getEmpId(), sqlAvatar);
			
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "index";
	/*	return "redirect:/to_index";*/
	}
}
